import React, { Component } from 'react'
import { View, Image, ScrollView, Canvas, Text, Button } from '@tarojs/components'
import Banner from '@/src/components/banner'
import Divider from '@/src/components/divider'
import DescRow from './components/desc-row'
import Global from '@/src/lib/global'
import Page from '@/src/components/page'
import Toolbar from './components/toolbar'
import Placeholder from '@/src/components/placeholder'
import Sheet from '@/src/components/sheet'
import Api from '@/src/lib/api/api'
import GoodsDetailModel from '@/src/lib/models/goods_detail_model'
import Taro from '@tarojs/taro'
import { connect } from 'react-redux'
import { State } from '@/src/dva/state'
import { CartState } from '@/src/dva/models/cart'

import GoodsCartModel from '@/src/lib/models/goods_cart_model'
import ServiceBtn from '@/src/components/service-btn'

import './index.scss'
import PageWarpper, { PageWarpperContext } from '@/src/components/page-warpper';

import Activity from './components/activity/Activity'

import { MovableArea, MovableView } from '@tarojs/components';

interface GoodsDetailProps {
    dispatch: any,
    cart: CartState,
    user: any
}

interface GoodsDetailState {
    requestCount: number,
    model?: GoodsDetailModel | any,
    cavansImg: string,
    goodData: any,
    evalatImage: string,
    isCavans: boolean,
    onSale: boolean,
    couponlist: any,
    obj: any,
    title: string,
    mansonglist: any,
    showPresent: boolean,
    rpx: any
}

class GoodsDetail extends Component<GoodsDetailProps, GoodsDetailState> {
    static contextType = PageWarpperContext

    goodsId = 0
    saleSheetRef = React.createRef<Sheet>()
    timer: any
    constructor(props: GoodsDetailProps) {
        super(props)

        this.state = {
            requestCount: 0,
            cavansImg: '',//生成海报的图片
            goodData: {},//商品详情
            evalatImage: '',//商品图片的临时路径,
            isCavans: false,//是否显示
            onSale: false,//是否显示领取优惠券组件
            couponlist: [],//优惠券数据
            obj: {
                d: 0,
                h: 0,
                m: 0,
                s: 0
            },//倒计时
            title: '秒杀',
            mansonglist: [
                { tip: 'sss' }
            ],
            showPresent: false,
            rpx: 0,
        }
    }
    // 领取优惠券
    onSaleRowClick = () => {
        // this.saleSheetRef.current?.show()
        this.setState({
            onSale: true
        })

    }
    onShareAppMessage() {
        let params = {
            id: this.goodsId
        }
        let pathUrl = `/pages/goodsdetail/index?params=${JSON.stringify(params)}`
        let model = this.state.model;
        let pic = model?.pic;
        return {
            title: '',
            // imageUrl:'http://r.punkyangsheng.com/xcx/img/images/share.png',
            imageUrl:pic,
            path: pathUrl
        }
    }
    onShareTimeline() {
        let params = {
            id: this.goodsId
        }
        let pathUrl = `/pages/goodsdetail/index?params=${JSON.stringify(params)}`
        let model = this.state.model;
        let pic = model?.pic;
        return {
            title: '',
            imageUrl:pic,
            path: pathUrl
        }
    }
    onShow() {
        clearInterval(this.timer)
    }

    onLoad(options) {
        let params = JSON.parse(options.params)
        this.goodsId = params.id
        this.requestGoodsInfo();
        // 获取优惠券列表
        this.getgoodsnList()
        let that = this;
        Taro.getSystemInfo({
            success: function (res) {
                let rpx = res.windowWidth / 375;
                that.setState({
                    rpx
                })
            },
        })

    }
    componentDidHide() {
        console.log('离开页面')
        clearInterval(this.timer)

    }
    onHide() {
        console.log('离开页面')
        clearInterval(this.timer)

    }
    //   获取海报的底部图片
    getCancas = () => {
        console.log(this.props)
        const { userInfo } = this.props.user
        const userName = userInfo.nickname;
        console.log('goodData', this.state.goodData);
        const img = this.state.goodData.piclist[0].pic.replace(/http/g, 'https');
        console.log('img', img)
        Taro.getImageInfo({
            src: img,
            success: (res) => {
                console.log("banner临时路径:" + res.path);
                this.setState({
                    evalatImage: res.path
                }, () => {
                    this.setCavns(userName)
                })
            },
            fail: res => {
                console.log('res', res)
                // this.getCancas()
            }
        })
        // const dpr = Taro.getSystemInfoSync().pixelRatio


    }
    setCavns = (userName) => {
        let context = Taro.createCanvasContext("goods-share-canvas")
        let rpx = this.state.rpx;
        context.clearRect(0, 0, 300 * rpx, 415 * rpx);
        context.setFillStyle("#fff")
        context.fillRect(0, 0, 300 * rpx, 415 * rpx)
        const titl = "几甜研究所官方店";
        context.setFontSize(14 * rpx);
        context.setFillStyle('#444');
        context.setTextAlign('center');
        context.font = 'PingFangSC-Medium, PingFang SC';
        context.fillText(titl, 150 * rpx, 30 * rpx);
        context.stroke();
        context.save();
        // 画邀请人
        const invite = `来自(${userName})的推荐`
        context.setFontSize(12 * rpx);
        context.setFillStyle('#999');
        context.setTextAlign('center');
        context.font = 'PingFangSC-Regular, PingFang SC';
        context.fillText(invite, 150 * rpx, 50 * rpx);
        context.stroke();
        context.save();
        // 画图片
        const path1 = this.state.evalatImage;
        // 绘制圆角图片
        // 图片的x坐标
        let bg_x = 40 * rpx
        // 图片的y坐标
        let bg_y = 60 * rpx
        // 图片宽度
        let bg_w = 220 * rpx
        // 图片高度
        let bg_h = 250 * rpx
        // 图片圆角
        // let bg_r = 7 * rpx

        // 绘制海报背景图片圆角
        context.save()
        // context.beginPath()
        // context.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
        // context.arc(bg_x + bg_w - bg_r, bg_y + bg_r, bg_r, Math.PI * 1.5, Math.PI * 2)
        // context.arc(bg_x + bg_w - bg_r, bg_y + bg_h - bg_r, bg_r, 0, Math.PI * 0.5)
        // context.arc(bg_x + bg_r, bg_y + bg_h - bg_r, bg_r, Math.PI * 0.5, Math.PI)
        // context.clip()
        context.drawImage(path1, bg_x, bg_y, bg_w, bg_h)
        context.restore()
        // 绘制价格
        const pros = this.state.goodData.realprice;
        console.log(pros)
        const price = `¥${pros}`
        context.setFontSize(20 * rpx);
        context.setFillStyle('#EFCE8F');
        context.setTextAlign('left');
        context.font = 'PingFangSC-Semibold, PingFang SC';
        context.fillText(price, 30 * rpx, 350 * rpx);
        context.stroke();
        context.save();
        // 绘制说明语境
        const kouwei = this.state.goodData.tip ? this.state.goodData.tip : this.state.goodData.title;
        let kouweis = '';
        let kouweis2 = ''
        if (kouwei.length > 13) {
            kouweis = kouwei.substring(0, 13);
            kouweis2 = kouwei.substring(13);
            context.setFontSize(14 * rpx);
            context.setFillStyle('#000');
            context.setTextAlign('left');
            context.font = 'PingFangSC-Semibold, PingFang SC';
            context.fillText(kouweis, 30 * rpx, 370 * rpx);
            context.stroke();
            context.save();
            if (kouweis2.length > 0) {
                if (kouweis2.length > 13) {
                    kouweis2 = `${kouweis2.substring(0, 10)}...`
                    context.setFontSize(14 * rpx);
                    context.setFillStyle('#000');
                    context.setTextAlign('left');
                    context.font = 'PingFangSC-Semibold, PingFang SC';
                    context.fillText(kouweis2, 30 * rpx, 390 * rpx);
                    context.stroke();
                    context.save();
                } else {
                    context.setFontSize(14 * rpx);
                    context.setFillStyle('#000');
                    context.setTextAlign('left');
                    context.font = 'PingFangSC-Semibold, PingFang SC';
                    context.fillText(kouweis2, 30 * rpx, 390 * rpx);
                    context.stroke();
                    context.save();
                }
            }
        } else {
            context.setFontSize(14 * rpx);
            context.setFillStyle('#000');
            context.setTextAlign('left');
            context.font = 'PingFangSC-Semibold, PingFang SC';
            context.fillText(kouwei, 30 * rpx, 370 * rpx);
            context.stroke();
            context.save();
        }

        const path2 = '/resources/images/weima.jpg'
        context.drawImage(path2, 200 * rpx, 330 * rpx, 70 * rpx, 70 * rpx);
        context.draw()

        setTimeout(() => {
            Taro.canvasToTempFilePath({
                x:0,
                y:0,
                // width: 350*rpx,
                // height:500*rpx,
                destWidth: 750*rpx,
                destHeight:940*rpx,
                // fileType: 'jpg',
                // quality: 1,
                canvasId: 'goods-share-canvas',
                success: (res) => {
                    var tempFilePath = res.tempFilePath;
                    this.setState({
                        cavansImg: tempFilePath
                    })
                    Taro.hideLoading()
                },
                fail: function (res) {
                    console.log(res);
                }
            });
        }, 2000)
    }

    /**
     * 请求商品信息
     */
    requestGoodsInfo = () => {
        Taro.showLoading()
        Api.goodsGoodsInfo({ id: this.goodsId }).then((res) => {
            // console.log('res',res)
            Taro.hideLoading()
            do {
                if (!res) {
                    break
                }

                if (!res.issuccess) {
                    Global.showToast(res.msg)
                    break
                }
            } while (false);
            if (res?.data.activity.end_time && (res?.data.activity.type === '1' || res?.data.activity.type === '3')) {
                this.countDown(res?.data.activity.end_time)
            }
            this.setState({
                requestCount: this.state.requestCount + 1,
                model: res?.data,
                goodData: res?.data,
                mansonglist: res?.data.activity.mansonglist
            })

        }).catch((err?: any) => {
            Taro.hideLoading()
            this.setState({
                requestCount: this.state.requestCount + 1
            })
            console.log(err)
        })
    }

    onShopBtnClick = () => {
        Taro.switchTab({ url: "/pages/home/index" })
    }

    onCartBtnClick = () => {
        Taro.switchTab({ url: "/pages/shopcart/index" })
    }

    onAddToCartBtnClick = () => {

        if (!Global.isLogin()) {
            let ctx = this.context
            ctx.loginCompentRef.current.show()
            return
        }

        const { dispatch } = this.props

        dispatch({
            type: "cart/add",
            payload: {
                goodsid: this.goodsId
            }
        })
    }

    onBuyBtnClick = () => {
        if (!Global.isLogin()) {
            let ctx = this.context
            ctx.loginCompentRef.current.show()
            return
        }

        const { model } = this.state
        if (!model) {
            return
        }

        let pic = ""
        let type = '-1'
        if (model.piclist.length > 0) {
            pic = model.piclist[model.piclist.length - 1].pic
        }
        if (model.activity.type) {
            model.realprice = model.activity.price;
            type = model.activity.type
        }

        let cartModel: GoodsCartModel|any = {
            goodsid: this.goodsId.toString(),
            hanliang: model.hanliang,
            id: "",
            kouwei: model.kouwei,
            num: "1",
            pic: pic,
            realprice: model.realprice,
            showprice: model.showprice,
            tip: model.tip,
            title: model.title,
            type: type,//类型
            loc_isSelling: true,
            orderid: '',//拼团订单的id
        }

        Global.redirectTo("/pages/order-confirm/index", {
            package: "subpackages",
            params: {
                models: [cartModel]
            }
        })
    }

    // 分享海报
    shareCanvas = () => {
        // 判断是否登录
        const { user } = this.props
        // console.log(user);
        const { loginCompentRef } = this.context
        if (!user.isLogin) {
            loginCompentRef.current.show()
            return
        }
        // if (this.state.cavansImg) {
        //     this.setState({
        //         isCavans: true
        //     })
        //     return
        // }
        Taro.showLoading({
            title: '图片生成中'
        })
        this.setState({
            isCavans: true
        }, () => {
            this.getCancas()
        })
    }
    // 保存图片
    saveImg = () => {
        var that = this
        Taro.saveImageToPhotosAlbum({
            filePath: that.state.cavansImg,
            success(res: any) {
                console.log(res)
                Taro.showModal({
                    content: '保存成功',
                    showCancel: false,
                    confirmText: '好的',
                    confirmColor: '#333',
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            /* 该隐藏的隐藏 */
                            that.setState({
                                isCavans: false
                            })
                        }
                    }, fail: function (res: any) {
                        console.log(res)
                        console.log(11111)
                    }
                })
            }
        })
    }
    // 预览图片
    preview = () => {
        const imgList: any = [];
        imgList.push(this.state.cavansImg)
        Taro.previewImage({
            current: this.state.cavansImg, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
    }
    // 取消
    quxiao = () => {
        this.setState({
            isCavans: false
        })
    }
    // 获取优惠券列表
    getgoodsnList = async () => {
        const data: any = await Api.goodsCouponList()
        const { couponlist } = data.data;
        console.log(couponlist)
        this.setState({
            couponlist
        })

    }
    // 领取优惠券
    getTicket = (e, id: string) => {
        e.preventDefault()
        e.stopPropagation();
        // e.nativeEvent.stopImmediatePropagation();
        console.log('id', id)
        Api.goodsCouponGet({ id }).then((res: any) => {
            console.log(res)
            if (res.issuccess != 1) {
                Taro.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            Taro.showToast({
                title: '领取成功',
                icon: 'none',
                duration: 2000
            })
            this.setState({
                couponlist: res.data.couponlist,
                onSale: false
            })
        })
    }
    // 关闭弹窗
    setonSale = () => {
        this.setState({
            onSale: false
        })
    }
    // 倒计时
    creaCountDown = () => {
        clearInterval(this.timer)
    }

    countDown = (endTime) => {

        const end = endTime.replace(/\./g, '/')
        console.log('end', end)
        const endTims = new Date(end).getTime();
        this.timer = setInterval(() => {
            let date = new Date().getTime();
            let residueTime = endTims - date;
            let day = 0, hour = 0, minute = 0, second = 0;
            day = parseInt((residueTime / (24 * 60 * 60 * 1000)).toString());//天
            let shengyu = residueTime % (24 * 60 * 60 * 1000)
            hour = parseInt((shengyu / (60 * 60 * 1000)).toString())//时
            shengyu = shengyu % (60 * 60 * 1000)
            minute = parseInt((shengyu / (60 * 1000)).toString())//分
            shengyu = shengyu % (60 * 1000);
            second = Math.round(shengyu / 1000);
            // console.log('day', day)
            // console.log('hour', hour)
            // console.log('minute', minute)
            // console.log('second', second)
            if (day <= 0) {
                day = 0
            }
            if (hour <= 0) {
                hour = 0
            }
            if (minute <= 0) {
                minute = 0
            }
            if (second < 0) {
                second = 0
                clearInterval(this.timer)
                return
            }
            const obj = {
                d: day,
                h: hour,
                m: minute,
                s: second
            }
            this.setState({
                obj
            })
        }, 1000)
    }
    // 显示促销model
    showModel = () => {
        this.setState({
            showPresent: true
        })
        // console.log('ssss')
    }
    present = () => {
        this.setState({
            showPresent: false
        })
    }

    render() {
        const { requestCount, model, couponlist, obj, mansonglist, showPresent } = this.state
        const { cart } = this.props;
        const { activity } = this.state.goodData;
        // console.log('activity',activity)
        // const mansonglist = this.state.goodData.activity.mansonglist
        console.log('model', model)
        let body
        if (requestCount > 0 && !model) {
            body = <Placeholder desc="几甜酱已经努力为您加载了o(╥﹏╥)o" button="重新加载" onBtnClick={this.requestGoodsInfo} />
        } else if (model) {
            // console.log(model)
            body = (

                <View className='goods-detail'>
                    <ScrollView className="scrollview" scrollY enhanced showScrollbar={false} style={{ height: `calc(100% - 120rpx - ${Global.shared.safeBottom}px)` }}>
                        <Banner
                            className="banner"
                            items={model.piclist.map(({ pic }) => pic)} />

                        <View className={['profile', activity.type && activity.type !== '2' ? 'profiles' : ''].join(' ')}>

                            {/* 价格销量标题 */}
                            {
                                activity.type && activity.type !== '2' ? (<Activity obj={obj} title={this.state.title} price={model.showprice} activity={activity}></Activity>) : (
                                    <View className="profile-padding-warp">
                                        <View className="price-container">
                                            <View className="price">￥{model.realprice}</View>
                                            <View className="sales">月销 {model.sellnum}</View>
                                        </View>
                                    </View>
                                )
                            }




                            <View className="profile-padding-warp">
                                <View className="goods-title-container">
                                    <View className="goods-title">
                                        <Text className="goods-title"> {model.title} {model.tip} {model.kouwei} {model.hanliang}</Text>
                                    </View>
                                    <View className="goods-share" onClick={this.shareCanvas}>
                                        <Image src={Global.loadImage('fenxiang@3x.png',)} className="fenxiang"></Image>
                                        <Text className="fenx">分享</Text>
                                    </View>
                                </View>
                            </View>

                            <Divider width={40} color="white" />

                            <Divider width={18} color="#F6F6F6" />

                            {/* 优惠 */}
                            {/* <View className="profile-padding-warp">
                                <DescRow
                                    title="领券"
                                    titleColor="#EFCE8F"
                                    desc={model.discount}
                                    activity={model}
                                    showArrow
                                    onClick={this.onSaleRowClick} />
                            </View> */}

                            <View className="profile-padding-warp">
                                <Divider color="#F2F2F2" />
                            </View>
                            {/* 促销 */}

                            {
                                activity.type === '2' ? (<View className="profile-padding-warp">
                                    <DescRow
                                        title="促销"
                                        activity={model}
                                        onClick={this.showModel}
                                    />
                                </View>) : null
                            }

                            {/* 已选规格 */}
                            <View className="profile-padding-warp">
                                <DescRow title="已选" desc={`${model.kouwei} ${model.hanliang}`} />
                            </View>

                            <Divider width={18} color="#F6F6F6" />

                            {/* 保障 */}
                            <View className="profile-padding-warp">
                                <DescRow className="desc-row-guard" title="保障" desc="七天无理由·极速退款" />
                            </View>
                            <Divider color="#F6F6F6" width={25} />
                        </View>




                        <View className="detail" style={{ fontSize: "0" }}>
                            <View className="title">
                                商品详情
                            </View>

                            {
                                model.contentpiclist.map(({ pic }) => <Image mode="widthFix" src={pic} />)
                            }

                        </View>
                    </ScrollView>

                    {/* 底部栏 */}
                    <Toolbar
                        style={{ height: `calc(120rpx + ${Global.shared.safeBottom}px)` }}
                        inCartGoodsNum={cart.totalGoodsNum}
                        onShopBtnClick={this.onShopBtnClick}
                        onCartBtnClick={this.onCartBtnClick}
                        onAddToCartBtnClick={this.onAddToCartBtnClick}
                        onBuyBtnClick={this.onBuyBtnClick}
                        activity={activity}
                    />

                    {/* Sheet */}
                    <Sheet ref={this.saleSheetRef} title="优惠详情">
                        <View className="sheet-sale-desc">
                            <View>优惠</View>
                            <View>{model.discount}</View>
                        </View>
                    </Sheet>
                    <MovableView x="350" y="500" direction="all" className="movab1">
                    <ServiceBtn />
                    </MovableView>
                  
                </View>
            )
        }

        return (
            <Page is={true} creaTime={this.creaCountDown} navigationBar={{ title: "商品详情" }} fixed>
                 <MovableArea style=' width: 100%; height: 100%;'>
                {body}
                {
                    this.state.isCavans ? (<View className="pagesCavans" >
                        {
                             <Canvas className="goods-share-canvas" canvasId="goods-share-canvas" style={{ width: `${300*this.state.rpx}px`, height: `${415*this.state.rpx}px`,  margin: 'auto', marginBottom:'450rpx'}}></Canvas>
                        }
                                             <View className="cavansBOtom">
                            <View className="cavansTops ">
                                <View className="topsItms" onClick={this.saveImg}>
                                    <Image src={Global.loadImage('cavans2.png')} className="icons"></Image>
                                    <Text className="iconsText">保存图片</Text>
                                </View>
                                <Button className="topsItms topsItmsBtn" open-type="share">
                                    <Image src={Global.loadImage('cavans1.png')} className="icons"></Image>
                                    <Text className="iconsText">发送好友</Text>
                                </Button>
                            </View>
                            <View className="cavansWith"></View>
                            <View className="cavanscols" onClick={this.quxiao}>取消</View>
                        </View>
                    </View>) : null
                }

                {/* 领取优惠券 */}
                {
                    this.state.onSale ? (
                        <View className="onSaleonSale" onClick={this.setonSale}>
                            <View className="onsale">
                                <View className="saleTop dis">领取优惠劵</View>
                                <View className="scroc">
                                    <ScrollView scroll-y="true" style="height: 692rpx;">
                                        {
                                            couponlist.map(item => {
                                                return (
                                                    <View className={["items", item.ismember === '0' ? 'bgYlows' : item.ismember === '1' && item.isget != '1' ? 'bgRed' : item.isget === '1' ? 'bgGry' : ''].join(' ')} onClick={(e) => this.getTicket(e, item.id)}>
                                                        <View className="item_left">
                                                            <View className="let_top">¥{item.price}</View>
                                                            <View className="left_botm">{item.tip}</View>
                                                        </View>
                                                        <View className="item_mins">
                                                            <Text>{item.title}</Text>
                                                            {/* <Text>领取后{this.setDate(items.begintime,items.endtime)}天有效</Text> */}
                                                            <Text> 领取后{item.activedays}天有效</Text>
                                                            <Text>全部商品适用</Text>
                                                        </View>
                                                        <View className="item_rig">
                                                            <View className="rig_top dis">
                                                                {
                                                                    item.isget && item.isget === '1' ? '已领取' : '领取'
                                                                }
                                                            </View>
                                                            <View className="rig_borm" >{
                                                                item.ismember === '0' ? `消耗${item.needscore}积分领取` : '会员领取'
                                                            }</View>


                                                        </View>
                                                    </View>
                                                )
                                            })
                                        }

                                    </ScrollView>
                                </View>

                            </View>

                        </View>
                    ) : null
                }

                {/* 弹窗赠品 */}
                {
                    showPresent ? (<View className="present" onClick={this.present}>
                        <View className="present-btto">
                            <View className="heand" onClick={this.present}>
                                <Text className="xinaq">促销详情</Text>
                                <Image src={Global.loadImage('icon_close@3x.png')} className="images"></Image>
                            </View>
                            <View className="items">
                                <View className="itemsTop">
                                    <View className="topText1">优惠</View>
                                    {
                                        mansonglist.map(item => {
                                            return <View className="topText2">{item.tip}</View>
                                        })
                                    }

                                </View>
                                <View className="Images">
                                    {
                                        mansonglist.map(item => {
                                            return <Image src={item.pic} className="imagest"></Image>
                                        })
                                    }

                                </View>
                            </View>
                        </View>
                    </View>) : null
                }

                    </MovableArea>
            </Page>
        )
    }
}


export default connect((state: State) => ({ cart: state.cart, user: state.user }), (dispatch) => ({ dispatch }))(PageWarpper()(GoodsDetail))